package com.lizonghui.googleplay.views;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * Created by Administrator on 2016/6/23.
 * 自定义View,左右滑动时候，请求自己处理，父容器不拦截
 */
public class ChildViewPager extends ViewPager {

    private float mDownX;
    private float mDownY;

    public ChildViewPager(Context context) {
        super(context);
    }

    public ChildViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    //以下三个事件的处理顺序：1dispatchTouchEvent 2onInterceptTouchEvent 3onTouchEvent
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //不要去处理它，因为这个关系到事件传递能否走到ViewGroup的dispatchTouchEvent中，它是起到控制作用
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {

        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()){
            case MotionEvent.ACTION_MOVE:
                float moveX = ev.getRawX();
                float moveY = ev.getRawY();

                int diffX = (int) (moveX - mDownX + .5f);
                int diffY = (int) (moveY - mDownY + .5f);

                if(Math.abs(diffX) > Math.abs(diffY)){//左右滑动-->请求自己处理，父容器不拦截
                    getParent().requestDisallowInterceptTouchEvent(true);
                }else {
                    getParent().requestDisallowInterceptTouchEvent(false);
                }
                break;
            case MotionEvent.ACTION_UP:
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
            case MotionEvent.ACTION_DOWN:
                mDownX = ev.getRawX();
                mDownY = ev.getRawY();
                break;
        }

        return super.onTouchEvent(ev);
    }
}
